package com.shennong.service.impl;

import com.shennong.mapper.UserMapper;
import com.shennong.pojo.*;
import com.shennong.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 符整国
 * @version 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        LoginVO loginVO = userMapper.getByUsernameAndPassword(loginDTO);
        if (loginVO != null) {
            loginVO.setToken("token");
            return loginVO;
        }
        return null;
    }


    /**
     * 注册
     *
     * @param user
     */
    @Override
    @Transactional
    public void register(User user) {
        if (userMapper.getByUsername() != null) {
            throw new RuntimeException("用户名已存在");
        } else {
            user.setCreateTime(LocalDateTime.now());
            log.info("用户注册：{}", user);
            userMapper.insert(user);
        }
    }
    /**
     * 查询课程
     *
     * @param id
     * @return
     */
    @Override
    public List<Course> findAllCourseById(Integer id) {
        List<Course> courses = userMapper.getCourseByUserId(id);
        return courses;
    }


    /**
     * 查询所有课程
     *
     * @return
     */
    @Override
    public List<Course> findAllCourse() {
        List<Course> courses = userMapper.findAllCourse();
        return courses;
    }

    /**
     * 选课
     *
     * @param enrollment
     */
    @Override
    public void selectCourse(Enrollment enrollment) {
        userMapper.selectCourse(enrollment);
    }


    /**
     * 退课
     *
     * @param enrollment
     */
    @Override
    public void cancelCourse(Enrollment enrollment) {
        userMapper.cancelCourse(enrollment);
    }




    /**
     * 请假
     *
     * @param leave
     */
    @Override
    public void leave(Leave leave) {
        leave.setStatus(0);
        leave.setCreatedTime(LocalDateTime.now());
        leave.setUpdatedTime(LocalDateTime.now());
        userMapper.leave(leave);
    }


    /**
     * 查询请假信息
     *
     * @param id
     * @return
     */
    @Override
    public Leave getLeaveByUserId(Integer id) {
        Leave leave = userMapper.getLeaveByUserId(id);
        if (leave != null) {
            return leave;
        }
        return null;
    }
}
